# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

import urllib
from .saltapi import salt
from .models import Minion, Server, ProcRunning, ProcConfig, SysProc
from saltops.forms import PaginationForm

def query(req):
    minionId = req.GET['minionId']
    minion = Minion.objects.get(key = minionId)
    procs = ProcRunning.objects.filter(minion = minion)
    cfgs = ProcConfig.objects.filter(minion = minion)
    ## 将存在于ProcConfig表的进程项从ProcRunning列表中移出并为其标记状态
    ## 存在于ProcConfig但没有在ProcRunning表的, 标记为未运行

    procs = [proc.parse() for proc in procs]
    cfgs = [cfg.parse() for cfg in cfgs]

    pscmdList = [proc['psStr'] for proc in procs]
    cfgstrList = [cfg['psStr'] for cfg in cfgs]

    procInCfgs = []
    procNameIncfgs = []
    for pscmdIdx, pscmd in enumerate(pscmdList):
        for cfgstrIdx, cfgstr in enumerate(cfgstrList):
            if pscmd.find(cfgstr) > -1:
                try:
                    ## 已有同名进程
                    idx = procNameIncfgs.index(cfgs[cfgstrIdx]['name'])
                    procInCfgs[idx]['pids'].append(procs[pscmdIdx]['pid'])
                    if procs[pscmdIdx]['port']:
                        tmpProc['portsInUse'].append(procs[pscmdIdx]['port'])
                    tmpProc['status'] = 1
                except Exception, e:
                    print(e)
                    tmpProc = cfgs[cfgstrIdx]
                    tmpProc['pids'] = []
                    tmpProc['portsInUse'] = []
                    tmpProc['pids'].append(procs[pscmdIdx]['pid'])
                    ## 如果running进程端口号大于0
                    if procs[pscmdIdx]['port']:
                        tmpProc['portsInUse'].append(procs[pscmdIdx]['port'])
                    tmpProc['status'] = 1
                    procNameIncfgs.append(cfgs[cfgstrIdx]['name'])
                    procInCfgs.append(tmpProc)
    
    result = {
        'rows': procs,
        'total': len(procs),
        'procInCfgs': procInCfgs
    }
    return JsonResponse(result)

def create(req):
    result = {
        'code': 1,
        'msg': 'success'
    }
    key = req.POST.get('minionId')
    exists = Minion.objects.filter(key = key).exists()
    if not exists:
        result['code'] = -1
        result['msg'] = '目标minion节点不存在'
        return JsonResponse(result)

    cfg = {
        'minion': Minion.objects.get(key = key),
        'name': req.POST.get('name'),
        'user': req.POST.get('user', 'root'),
        'ports': req.POST.get('ports'),
        'path': req.POST.get('path'),
        'start_cmd': req.POST.get('startCmd'),
        'ps_str': req.POST.get('psStr'),
        'remark': req.POST.get('remark'),
    }
    try:
        ProcConfig.objects.create(**cfg)
        result['code'] = 1
        result['msg'] = 'success'
    except Exception, e:
        result['code'] = -1
        result['msg'] = '%s' % e
    return JsonResponse(result)

def delete(req):
    pass

def update(req):
    pass

